<?php


namespace app\sys\model;


use app\admin\model\Chat;
use app\admin\model\ChatLog;
use think\facade\Cache;
use think\facade\Log;
use think\Model;

class Hint extends Model
{
    protected $autoWriteTimestamp = true;

    public static function list()
    {
        $c = Hint::count();
        $l = Hint::field("*")->select();
        return listDate($l, $c);
    }

    public static function up($id, $text, $isTime)
    {
        Hint::where("id", $id)->data(["text" => $text, "is_time" => $isTime])->update();
    }

    public static function del($id)
    {
        Hint::where("id", $id)->delete();
    }

    public static function stat($id, $status)
    {
        $s = Hint::where("id", $id)->value("status");
        if ($s == $status) return "状态相同~";
        Hint::where("id", $id)->data(["status" => $status])->update();
        return "";
    }

    /**
     * 超时结束
     * redis
     */
    public static function chatTimeEnd()
    {
        $h = Cache::store("default")->handler();

        $h->subscribe(array("ChatTimeEnd"), function ($redis, $ch, $msg) {
            if ($ch == "ChatTimeEnd") {
                Log::info("chatTimeEnd1~$msg");
            }
            Log::info("chatTimeEnd1 ~ $ch~$msg");
        });
    }

    /**
     * 超时结束 - 数据库
     * chatTimeEnd
     */
    const chatTimeEnd = "ChatTimeEnd";

    public static function chatTimeEnd2()
    {
        $ti = strtotime("-10 minutes");
//        $ti = strtotime("-1 minutes");//测试
        $ni = strtotime(date("Y-m-d"));
        $res = Chat::field("id,user_id,staff_id")->where("update_time",">=",$ni)->where("update_time","<",$ti)->select();
        foreach ($res as $k => $v){
            $log = ChatLog::where("talk_no","")->where("chat_id",$v["id"])->where("send_to","<>","sys")->value("id");
            if($log){
                // 数据库记录
                $talkNo = time().rand(10,100);
                ChatLog::where("talk_no","")->where("chat_id",$v["id"])->data(["talk_no"=>$talkNo])->update();
                // 消息推送
                Chat::TisToUser($v["user_id"],$v["staff_id"],0,"超时结束");

                Log::info("chatTimeEnd2".$v);
            }
        }
        Log::info("chatTimeEnd2".$ti);
    }

    /**
     *
     */
    public static function getInfoByName($name)
    {
        return Hint::where("chat_name",$name)->value("text","");
    }
}